package project.web.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom.JDOMException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;

import fld.background.system.controller.BaseController;
import project.web.utils.HttpUtil;
import project.web.utils.PayCommonUtil;
import project.web.utils.XMLUtil;

/**
 * web首页-包图海外
 * @author yc
 * 2019年3月1日
 */
@Controller
@RequestMapping (value="/web/bthw")
public class WebBthwIndexController extends BaseController{
	
	private final static String MODEL_PATH = "web/bthw/";
	
	private final static String WXAPPID = "wx33908da29bbe88f8";
	private final static String WXSHH = "1523245221";
	private final static String WXNOFITY = "http://5i0z4.cn/web/bthw/wxNotify";
	private final static String WXAPISECRET = "f2hLKZSeuHQjP7QwhoxxeCWhl6TUKQK5";
	
	private final static String ZFBAPPID = "2018121462519868";
	private final static String ZFBAPPPRIVATEKEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC44Gx9XOibgQpPu9584dJ9Pw2mESHAFkPIFjT3a8ehz6P3uKx13mekX/vtPy09AkdBDqQ6O6qltYNKSgU/LWP9W/0U6Rj+n3GPrGnxDYiHvJtH++WM4mScyB9cEszcKf3aM1rXzjuA8TNlgE7uTMX0usBg+dzG9QHGYH8ECs1BZjeYu2AAd2AY3gKIwXh/3qsPx8kt3UCC4z1UApIOzsAisq20SisIudtO2PF2C5+Qcl6E02lJmhyT9IcBDtUSlsM7lUj9twZhKG1M5Qt67MHFAISig/z+b/c6OUC9gwEKs0rZP3Flt5sHgLTvr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iL4qXlJolgVVxfl7Lp2zC+0duCXBAoGANjIQGcyUgziryXp0M3iEEhIe7WbVhlrCGOhSzNHb1MlK8W6PjhHOFomfLErsLCOyLXDQ3644vjv2sIGnojodbWpGOGHxSI3b+D8Th2seLs2qek4aJTBwo1pSfWKr6vQCMHe869R3hP9fVop6nCATNl4W+BQQd4+R6eGEj8gO9qY=";
	private final static String ZFBALIPAYPUBLICKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgT2jLVhyblTLtj5ew/VVfIRXeuZe8/Vk1nJliFQ5XVu6OlS2yEbPFoon/fNQv0b4tV0zN/kchDzMEy2okNuPc6MMFc1Sgucc9vHpFj7d19aAy0BQhhpEzoujxs0IZ9Ti0tRO9HUVNnf3NHSJMw4NnWy0TbdAuD+AnBL8gWhptmHqgzr3iXvvhYfjNOLTRRpZbHn7QuH4khJc0jGuJRRjL1bRlEv34nqmTlwankoF5wm8AqFKM36qWkeIKqUvrYqGRe3PvZR8k7c8NvqJbDZyIy3AHIMpn1dP53VG05MnpAQOURHa0f3IPlNG2vijEsoAixD5a3PORIy2+s7NkQXFFwIDAQAB";
	/**
	 * 首页
	 * @return
	 * @author yc
	 * @date 2018年12月9日
	 */
	@RequestMapping(value="index")
	public ModelAndView index(){
		ModelAndView model = new ModelAndView();
		model.setViewName(MODEL_PATH+"index");
		model.addObject("webPage", "index");
		return model;
	}
	
	/**
	 * 简介
	 * @return
	 * @author yc
	 * @date 2018年12月9日
	 */
	@RequestMapping(value="payment")
	public ModelAndView payment(){
		ModelAndView model = new ModelAndView();
		model.setViewName(MODEL_PATH+"payment");
		model.addObject("webPage", "payment");
		return model;
	}

	/**
	 * 创建二维码
	 * @param type
	 * @param price
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 * 2019年3月1日
	 * @author yc
	 */
	@ResponseBody
	@RequestMapping(value="createQrCode")
	public JSONObject createQrCode(String price) throws JDOMException, IOException{
		JSONObject result = new JSONObject();
		String code1 = getWxUrl(price);
		String code2 = getZfbUrl(price);
		if("".equals(code2)) {
			result.put("success", false);
			return result;
		}
		result.put("code1", code1);
		result.put("code2", code2);
		result.put("success", true);
		return result;
	}
	
	@SuppressWarnings("rawtypes")
	public String getWxUrl(String price) throws JDOMException, IOException {
		String out_trade_no = createLsh();
		//微信支付
        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayCommonUtil.buildRandom(4) + "";
        String nonce_str = strTime + strRandom;

        int order_price = 0; // 价格   注意：价格的单位是分
        String body = "";   // 商品名称
        if("999".equals(price)) {
        	order_price = 99900;
        	body = "支付999";
		}else if("1999".equals(price)) {
			order_price = 199900;
        	body = "支付1999";
		}else if("2999".equals(price)) {
			order_price = 299900;
        	body = "支付2999";
		}
        // 回调接口
        String trade_type = "NATIVE";

        SortedMap<String, String> packageParams = new TreeMap<>();
        packageParams.put("appid", WXAPPID + "");
        packageParams.put("mch_id", WXSHH + "");
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);

        packageParams.put("attach","");
       // packageParams.put("out_trade_no", out_trade_no + "-lolsuper");
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("total_fee", order_price + "");
        packageParams.put("spbill_create_ip", InetAddress.getLocalHost().getHostAddress());//这里有个bug  经过转发之后的请求获取不到原来的IP而且转发两次之后会返回两个用逗号隔开的IP，微信会返回参数超长错误
        packageParams.put("notify_url", WXNOFITY);
        packageParams.put("trade_type", trade_type);

        String sign = PayCommonUtil.createSign("UTF-8", packageParams, WXAPISECRET);
        packageParams.put("sign", sign);

        String requestXML = PayCommonUtil.getRequestXml(packageParams);
        System.out.println(requestXML);

        String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);

        Map map = XMLUtil.doXMLParse(resXml);
        String urlCode = (String) map.get("code_url");
        return urlCode;
	}
	
	public String getZfbUrl(String price) {
		String out_trade_no = createLsh();
		//支付宝支付
        String order_price = price;
        String body = "";
        if("999".equals(price)) {
        	body = "支付999";
		}else if("1999".equals(price)) {
			body = "支付1999";
		}else if("2999".equals(price)) {
			body = "支付2999";
		}
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ZFBAPPID, ZFBAPPPRIVATEKEY, "json", "utf-8", ZFBALIPAYPUBLICKEY, "RSA2");
        AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
        alipayRequest.setReturnUrl("http://5i0z4.cn/protal/alipayNotify");
        alipayRequest.setNotifyUrl("http://5i0z4.cn/protal/alipayNotify");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "\"out_trade_no\":\"" + out_trade_no + "\"," +
                "\"total_amount\":" + order_price + "," +
                "\"subject\":\"" + body + "\"," +
                "\"body\":\"" + "\"," +
                "\"qr_code_timeout_express\":\"90m\"" +//设置二维码失效时长为90秒
                "  }");
        AlipayTradePrecreateResponse alipayResponse;
        try {
            alipayResponse = alipayClient.execute(alipayRequest);
            if (alipayResponse.isSuccess()) {
                String urlCode = alipayResponse.getQrCode();
                return urlCode;
            } else {
            	return "";
            }
        } catch (AlipayApiException e) {
        	return "";
        }
	}
	/**
     * 创建流水号
     * @return
     * 2018年8月8日
     * @author yc
     */
    private String createLsh(){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    	return sdf.format(new Date())+createSjs();
    }

    /**
     * 创建随机数
     * @return
     * 2018年8月8日
     * @author yc
     */
    private int createSjs() {
    	Random rand =new Random();
    	int i;
    	i=rand.nextInt(999999);
    	if(i < 100000)
    		i = createSjs();
    	return i;
    }
}
